import os
import re
from bottle import route, view
import mamba.config as config
from mamba.utils import Item, Action

@route("/videosources")
@view("list")
def videos():
	items = []
	if "videos" in config.config():
		for source, path in config.config()["videos"].items():
			items.append(Item(id=source, action="videolist/" + path))
	return dict(goback=True, items=items)

@route("/videolist/<dir:path>")
@view("list")
def list(dir):
	items = []
	for dirpath, dirnames, filenames in os.walk(dir):
		for filename in filenames:
			if not filename.startswith("."):
				items.append(Item(id=filename, text=videotitle(filename), action="videoplayer/" + os.path.join(dirpath, filename)))
	return dict(goback = True, items=items)

@route("/videoplayer/<filepath:path>")
@view("videoplayer")
def player(filepath):
	return dict(videotitle=videotitle(filepath), src="file/" + filepath, osd="video/osd")

@route("/video/osd")
@view("list")
def osd():
	items = osditems()
	return dict(goback=True, items=items, cls="center")

def osditems():
	return [Item(id="playpause", text="▶  ❚❚", action=Action("playpause(); hideOsd()", javascript=True)),
	         Item(id="stop", text="■ ", action=Action("stop();", javascript=True)),
	         Item(id="fastforward", text="▶▶", action=Action("fastforward();", javascript=True)),
	         Item(id="rewind", text="◀◀", action=Action("rewind();", javascript=True))
	]
 

@route("/cutter:file")
def cutter(file=None):
	pass

def videotitle(filepath):
	return " ".join(re.split("[\W_]", os.path.splitext(os.path.basename(filepath))[0]))

#	imdb_server = "http://www.imdb.com"
#	query = "/xml/find?xml=1&nr=1&tt=on&q=" + " ".join(match.group() for match in re.findall("[a-zA-Z0-9]+", os.path.splitext(filename)[0])
#	imdb = HTTPConnection(imdb_server)
#	imdb.request("GET", query)
#	xml = imdb.getresponse()
	
